import { IPortalMessage } from '@ibiz-template/core';
import { MqttClient, IClientOptions } from 'mqtt';
import { QXEvent, createUUID } from 'qx-util';

/**
 * mqtt 连接服务
 *
 * @author chitanda
 * @date 2023-10-20 14:10:40
 * @export
 * @class MqttService
 */
export class MqttService {
  /**
   * 接受消息通知
   *
   * @author chitanda
   * @date 2023-10-23 15:10:06
   */
  readonly evt: QXEvent<{ message: (msg: IPortalMessage) => void }> =
    new QXEvent();

  /**
   * mqtt 连接实例
   *
   * @author chitanda
   * @date 2023-10-20 20:10:44
   * @type {MqttClient}
   */
  client?: MqttClient;

  /**
   * 连接选项
   *
   * @author chitanda
   * @date 2023-10-20 14:10:25
   * @protected
   * @type {IClientOptions}
   */
  protected options: IClientOptions = {
    // 超时时间
    connectTimeout: 6000,
    // 认证信息
    clientId: createUUID(),
    username: '',
    password: '',
    // 心跳时间
    keepalive: 60,
    clean: true,
  };

  /**
   * Creates an instance of MqttService.
   *
   * @author chitanda
   * @date 2023-10-23 15:10:06
   * @param {string} mqttTopic
   * @param {string} token
   * @param {string} appId
   */
  constructor(
    protected mqttTopic: string,
    protected token: string,
    protected appId: string,
  ) {
    this.options.username = mqttTopic;
    this.options.password = token;
  }

  /**
   * mqtt 连接
   *
   * @author chitanda
   * @date 2023-10-23 15:10:58
   * @return {*}  {Promise<void>}
   */
  async connect(): Promise<void> {
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    // const module = await import('mqtt/dist/mqtt.min');
    // const mqtt = module.default ? module.default : module;
    // const { location } = window;
    // this.client = mqtt.connect(
    //   `ws://${location.host}${ibiz.env.baseUrl}/${this.appId}${ibiz.env.mqttUrl}`,
    //   this.options,
    // ) as MqttClient;
    // this.client.on('connect', () => {
    //   this.client!.subscribe(this.mqttTopic);
    //   ibiz.log.debug('mqtt connect');
    // });
    // this.client.on('error', error => {
    //   ibiz.log.error('mqtt error', error);
    // });
    // this.client.on('message', (topic, payload) => {
    //   this.evt.emit('message', JSON.parse(payload.toString()));
    //   ibiz.log.debug('mqtt message', topic, payload.toString());
    // });
    // this.client.on('reconnect', () => {
    //   ibiz.log.warn('mqtt reconnect');
    // });
    // this.client.on('close', () => {
    //   ibiz.log.warn('mqtt close');
    // });
  }

  /**
   * 结束 mqtt 连接
   *
   * @author chitanda
   * @date 2023-10-23 15:10:37
   */
  close(): void {
    this.client?.end();
    this.evt.reset();
  }
}
